﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using WmsApp.Export;
using WmsApp.Service;
using WmsApp.StaticData;
using WmsApp.StaticData.Unity;
using WmsApp.Style;
using WmsApp.UI;
using WmsApp.WindowControl;
using WmsApp.WmsService;

namespace WmsApp.Window
{
    public partial class FormIn : BaseForm
    {
        private BaseGoodsCodeTypeObserver goodsCodeTypeObserver = null;
        private InStoreBillController inStoreBillController = null;
        public FormIn()
        {
            InitializeComponent();
            
            if (GlobalClass.RunTimeMode)
            {
                inStoreBillController = new InStoreBillController(this.textEditBillID3, this.lookUpEditProvider3,
                                                                  this.textEditProviderName3,
                                                                  this.dateEditBillDate3, this.textEditInBillStateDesc3,
                                                                  this.gridControlEdit3, this.lookUpEditInStoreType3,
                                                                  this.gridControlInvoiceBill,
                                                                  this.textEditRequisitionNo3,
                                                                  this.textEditPurchaseName3,
                                                                  this.textEditProjectNo3,
                                                                  this.textEditKeeperName3,
                                                                  this.textEditContractNo3,
                                                                  this.textEditCheckerName3,
                                                                  this.memoEditRemark3,
                                                                  this.lookUpEditPurchaseID3,
                                                                  this.lookUpEditKeeperID3,
                                                                  this.lookUpEditCheckerID3,
                                                                  this.comboBoxEditPurchaseID3,
                                                                  this. comboBoxEditKeeperID3,
                                                                  this. comboBoxEditCheckerID3,
                                                                  this.dateEditInBillDate3);

                inStoreBillController.CustomInStoreBillId = this.checkEditCustomerInStoreBillID;
                //绑定静态数据
                inStoreBillController.BindingStaticData();

                inStoreBillController.SumAmountChanged += () =>
                                                              {
                                                                  this.textEditSumInStoreBillDtl.Text =
                                                                      inStoreBillController.GetTotalInStoreBillDtlAmount
                                                                          ().ToString();
                                                                  this.textEditSumInvoiceBill.Text =
                                                                      inStoreBillController.GetTotalInvoiceBillAmount().
                                                                          ToString();
                                                              };
                //自动计算checkbox挂委托
                this.checkEditAutoCompute.CheckedChanged += (o, e) => AutoCompute(checkEditAutoCompute.Checked);
                //先执行一次
                AutoCompute(checkEditAutoCompute.Checked);

                //LookupBind.BindingComboBoxSpecificationType(this.gridView3,this.gridColumn45,base.RepComboBox);)
                try
                {
                    var subject = StaticData.GoodsCodeTypeSubjectFactory.GetGoodsCodeTypeSubject();
                    goodsCodeTypeObserver = new GoodsCodeTypeObserver("in",subject,
                                                                      inStoreBillController.FRepositoryItemGridLookUpEdit,this);
                    subject.Attach(goodsCodeTypeObserver);

                    //重构后的代码规范，就一句话
                    SubjectFactory.AddObserverToSubject(new CustomerObserver("customer", SubjectFactory.GetSubject(),this.lookUpEditProvider3.Properties,this));
                }
                catch(Exception ex)
                {
                    Exceptions.ExceptionHandler.ShowException(ex);
                }
            }
        }

        /// <summary>
        /// 是否自动计算单价含税/不含税，总价（含税/不含税）
        /// </summary>
        /// <param name="isAutoCompute"></param>
        private void AutoCompute(bool isAutoCompute)
        {
            this.inStoreBillController.BAutoComputeTax = isAutoCompute;
            if (isAutoCompute)//分别为总价含税/总价不含税两个字段
            {
                this.gridColumn34.OptionsColumn.AllowEdit = false;
                this.gridColumn35.OptionsColumn.AllowEdit = false;
            }
            else
            {
                this.gridColumn34.OptionsColumn.AllowEdit = true;
                this.gridColumn35.OptionsColumn.AllowEdit = true;
            }
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            this.gridControlInvoiceBill.Left = this.CmdNewInvoiceBill.Left + this.CmdNewInvoiceBill.Width + 5;
            this.gridControlInvoiceBill.Width = groupControl1.Width - 5 - this.CmdNewInvoiceBill.Left -
                                                this.CmdNewInvoiceBill.Width;
            this.CmdQuery.Left = this.qInStoreBill1.Left + qInStoreBill1.Width;
            this.CmdNew.Left = this.qInStoreBill1.Left + qInStoreBill1.Width;
            this.CmdEdit1.Left = this.qInStoreBill1.Left + qInStoreBill1.Width;
            this.CmdImportOutBill.Left = this.qInStoreBill1.Left + qInStoreBill1.Width;
        }

        public override string HeadText
        {
            get { return "入库管理"; }
        }

        private void CmdEnableControl()
        {
            if (this.inStoreBillController.BillState == Constant.BillStateDraft)
            {
                this.CmdSave3.Enabled = true;
                this.CmdNewDtl3.Enabled = true;
                this.CmdInAffirm3.Enabled = true;
                this.CmdImport.Enabled = true;

                this.lookUpEditInStoreType3.Enabled = true;
                this.lookUpEditProvider3.Enabled = true;
                //this.dateEditBillDate3.Enabled = true;
                this.CmdDelete.Enabled = true;
                this.CmdNewInvoiceBill.Enabled = true;
                this.CmdDeleteInvoice.Enabled = true;
                this.textEditRequisitionNo3.Enabled = true;
                this.textEditPurchaseName3.Enabled = true;
                this.textEditProjectNo3.Enabled = true;
                this.textEditKeeperName3.Enabled = true;
                this.textEditContractNo3.Enabled = true;
                this.textEditCheckerName3.Enabled = true;
                this.memoEditRemark3.Enabled = true;
                this.lookUpEditPurchaseID3.Enabled = true;
                this.lookUpEditKeeperID3.Enabled = true;
                this.lookUpEditCheckerID3.Enabled = true;
                this.dateEditInBillDate3.Enabled = true;

                this.comboBoxEditCheckerID3.Enabled = true;
                this.comboBoxEditKeeperID3.Enabled = true;
                this.comboBoxEditPurchaseID3.Enabled = true;
            }
            else
            {
                this.CmdSave3.Enabled = false;
                this.CmdNewDtl3.Enabled = false;
                this.CmdInAffirm3.Enabled = false;
                this.CmdImport.Enabled = false;
                this.lookUpEditInStoreType3.Enabled = false;
                this.lookUpEditProvider3.Enabled = false;
                //this.dateEditBillDate3.Enabled = false;
                this.CmdDelete.Enabled = false;
                this.CmdNewInvoiceBill.Enabled = false;
                this.CmdDeleteInvoice.Enabled = false;
                this.textEditRequisitionNo3.Enabled = false;
                this.textEditPurchaseName3.Enabled = false;
                this.textEditProjectNo3.Enabled = false;
                this.textEditKeeperName3.Enabled = false;
                this.textEditContractNo3.Enabled = false;
                this.textEditCheckerName3.Enabled = false;
                this.memoEditRemark3.Enabled = false;
                this.lookUpEditPurchaseID3.Enabled = false;
                this.lookUpEditKeeperID3.Enabled = false;
                this.lookUpEditCheckerID3.Enabled = false;
                this.dateEditInBillDate3.Enabled = false;

                this.comboBoxEditCheckerID3.Enabled = false;
                this.comboBoxEditKeeperID3.Enabled = false;
                this.comboBoxEditPurchaseID3.Enabled = false;
            }
        }


        #region 按钮事件
        private void CmdNew3_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.NewInStoreBill();
            CmdEnableControl();
        }

        private void CmdNewDtl3_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.AddInStoreBillDtl();
            CmdEnableControl();
        }

        private void CmdSave3_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.SaveInStoreBill();
            CmdEnableControl();
        }

        private void CmdInAffirm3_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.AffirmInStoreBill();
            //this.inStoreBillController.LoadInStoreBill(this.inStoreBillController.CurrentBillID);
            CmdEnableControl();
        }

        private void CmdNew_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.NewInStoreBill();
            this.xtraTabControlMain.SelectedTabPage = this.xtraTabPage3;
            CmdEnableControl();
        }

        /// <summary>
        /// 查询入库单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdQuery_Click(object sender, EventArgs e)
        {
            IEntityService<InStoreBill, InStoreBillService> service =
                EntityServiceFactory.GetEntityService<InStoreBill, InStoreBillService>();
            IQueryControl qControl = this.qInStoreBill1;
            this.gridControlEdit1.DataSource = service.GetEntityList(qControl.GetCondition());
            RowStyleConditionController.AddStyleFormatCondition(this.gridView1, "BillStateDesc", "[BillStateDesc] != '确认'");
        }

        private void CmdNew2_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.NewInStoreBill();
            this.xtraTabControlMain.SelectedTabPage = this.xtraTabPage3;
            CmdEnableControl();
        }

        /// <summary>
        /// 查询入库明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdQuery2_Click(object sender, EventArgs e)
        {
            //IEntityService<InStoreBillDtl, InStoreBillDtlService> service =
            //        EntityServiceFactory.GetEntityService<InStoreBillDtl, InStoreBillDtlService>();
            //IQueryControl queryControl = this.qInStoreBillDtl1;
            //this.gridControlEdit2.DataSource = service.GetEntityList(queryControl.GetCondition());

            IEntityService<VInStoreBillDtlAndHead, VInStoreBillDtlAndHeadService> service =
        EntityServiceFactory.GetEntityService<VInStoreBillDtlAndHead, VInStoreBillDtlAndHeadService>();
            IQueryControl queryControl = this.qInStoreBillDtl1;
            this.gridControlEdit2_2.DataSource = service.GetEntityList(queryControl.GetCondition());
        }

        private void CmdEdit1_Click(object sender, EventArgs e)
        {
            var obj = this.gridView1.GetFocusedRow();
            if (obj != null)
            {
                this.inStoreBillController.LoadInStoreBill(((InStoreBill)obj).BillID);
                this.xtraTabControlMain.SelectedTabPage = this.xtraTabPage3;
                CmdEnableControl();
            }
        }

        private void CmdEdit2_Click(object sender, EventArgs e)
        {
            var obj = this.gridView2.GetFocusedRow();
            if (obj != null)
            {
                this.inStoreBillController.LoadInStoreBill(((VInStoreBillDtlAndHead)obj).BillID);
                this.xtraTabControlMain.SelectedTabPage = this.xtraTabPage3;
                CmdEnableControl();
            }
        }

        private void CmdDelete_Click(object sender, EventArgs e)
        {
            var obj = this.gridView3.GetFocusedRow();
            if (obj != null)
            {
                this.inStoreBillController.RemoveInStoreBillDtl((InStoreBillDtl)obj);
                CmdEnableControl();
            }
        }

        private void CmdPayApplyBill_Click(object sender, EventArgs e)
        {
            //if(this.inStoreBillController.BillState == Constant.BillStateDraft)
            //{
            //    XtraMessageBox.Show("入库单为草稿状态不能产生付款申请单！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            var form = new FormPayApplyBillEditor(String.Empty);
            form.ShowDialog();
        }

        private void CmdNewInvoiceBill_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.AddInvoiceBill();
        }

        private void CmdDeleteInvoice_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.DeleteInvoiceBillFromInStoreBill();
        }

        private void CmdPrint_Click(object sender, EventArgs e)
        {
            this.inStoreBillController.Print();
        } 

        private void CmdImportOutBill_Click(object sender, EventArgs e)
        {
            try
            {
                var form = new FormImportOutStoreBill();
                if (System.Windows.Forms.DialogResult.OK == form.ShowDialog())
                {
                    var inStoreBill = Factory.WmsServiceFactory.GetServiceClient().ImportInStoreBillFromOutStoreBill2(
                        form.POutStoreBill.BillID);
                    this.inStoreBillController.LoadInStoreBill(inStoreBill);
                    this.xtraTabControlMain.SelectedTabPage = this.xtraTabPage3;
                    CmdEnableControl();
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        private void CmdImport_Click(object sender, EventArgs e)
        {
            try
            {
                if(this.inStoreBillController== null || String.IsNullOrEmpty(this.inStoreBillController.CurrentBillID))
                {
                    return;
                }
                var openFileDialog = new OpenFileDialog {Filter = @"*.xls|*.xls"};
                if (System.Windows.Forms.DialogResult.OK == openFileDialog.ShowDialog())
                {
                    var list = ExcelImportor.ReadGoodsCodeTypeFromExcel(openFileDialog.FileName, this.inStoreBillController.CurrentBillID);
                   
                    this.inStoreBillController.AddInStoreBillDtl(list);
                }
            }
            catch (Exception exception)
            {
                Exceptions.ExceptionHandler.ShowException(exception);
            }
        }   

        private void CmdRefresh_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.DialogResult.Yes == XtraMessageBox.Show("确实要重新加载吗？", "提问", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                this.inStoreBillController.RefreshInStoreBill();
            }
        }     
        
        private void CmdUpdateNewGoodsCode_Click(object sender, EventArgs e)
        {
            if(this.inStoreBillController != null && this.inStoreBillController.PColumnExtraButtonAttacher != null)
            {
                this.inStoreBillController.PColumnExtraButtonAttacher.EditGoodsCodeType();
            }
        }

        private void CmdAddNewGoodsCode_Click(object sender, EventArgs e)
        {
            if (this.inStoreBillController != null && this.inStoreBillController.PColumnExtraButtonAttacher != null)
            {
                this.inStoreBillController.PColumnExtraButtonAttacher.AddGoodsCodeType();
            }
        }

        private void CmdUpdateProvider_Click(object sender, EventArgs e)
        {
            if(this.inStoreBillController != null)
            {
                try
                {
                    inStoreBillController.UpdateProvider();
                }
                catch (Exception exception)
                {
                   Exceptions.ExceptionHandler.ShowException(exception);
                }
            }
        } 
        #endregion
    }
}